import router from "./index";
import { getToken } from "../utils/app";
import store from "../store/index";

const whiteList = ["/login"];

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = getToken();
  if (token || whiteList.includes(to.path)) {
    // 已经登录过了 但用户又自己跳转到了login页 则直接返回到后台主页
    if (to.path === "/login" && token) {
      return next("/index");
    }

    if (store.getters["app/roles"].length === 0) {
      store.dispatch("permission/getRoles").then(res => {
        const role = res;
        store.dispatch("permission/createRouter", role).then(res => {
          const addRoutes = store.getters[`permission/addRoutes`];
          const allRoutes = store.getters[`permission/allRoutes`];
          // ↓更新options,左侧导航会用到
          router.options.routes = allRoutes;
          // 使路由生效
          router.addRoutes(addRoutes);
          next({ ...to, replace: true });
        });
      });
    } else {
      next();
    }
  } else {
    next("/login");
  }

  // next(); // 允许进入到该路由
  // next("/index"); // 跳转到指定路由,注意可能发生死循序
});
